For swift 5.2
I made some adjustments to meet my requirements
- Not to scroll if the content didn't extend outside the screen
- Center if the content didn't extend outside the screen
- If the content did extend outside the screen make sure to start at index 0 and allow scrolling while indenting from the edge by 16 (easy to adjust)
func centerItemsInCollectionView(cellWidth: Double, numberOfItems: Double, spaceBetweenCell: Double, collectionView: UICollectionView) -> UIEdgeInsets {
let totalWidth = cellWidth * numberOfItems
let totalSpacingWidth = spaceBetweenCell * (numberOfItems - 1)
let leftInset = (collectionView.frame.width - CGFloat(totalWidth + totalSpacingWidth)) / 2
let rightInset = leftInset
if leftInset < 0 {
collectionView.isScrollEnabled = true
return UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
}
collectionView.isScrollEnabled = false
return UIEdgeInsets(top: 0, left: leftInset, bottom: 0, right: rightInset)
}
Use this by doing this in your view controller
extension BaseViewController : UICollectionViewDelegateFlowLayout {
then you can call
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return centerItemsInCollectionView(cellWidth: 70, numberOfItems: 3, spaceBetweenCell: 25, collectionView: collectionView)
}
keep in mind if you want to set your own size for your cells you need to set the collectionView Estimated Size to none in storyboard and set your cells size to custom in storyboard
then you can call
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize.init(width:60, height: 60)
}
if you are struggling to get methods to get called it's good to get all your delegates listened for
extension BaseViewController : UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
and obviously don't forget to set your delegates, simply extending them won't do the trick.
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
...